package com.feige.helper;

import com.feige.pojo.Permission;
import com.feige.pojo.vo.FrontRouteVo;
import com.feige.pojo.vo.MetaVo;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 根据权限数据构建登录用户左侧菜单数据
 * @author
 * @since
 */
public class MenuHelper {

    /**
     * 填充实体
     * @param permission
     * @return
     */
    private static FrontRouteVo fillEntity(Permission permission){
        MetaVo metaVo = new MetaVo();
        metaVo.setIcon(permission.getIcon())
                .setTitle(permission.getName());
        FrontRouteVo frontRouteVo = new FrontRouteVo();
        frontRouteVo.setName(getRouteName(permission));
        frontRouteVo.setPath(getRouterPath(permission));
        frontRouteVo.setComponent(getComponent(permission));
        frontRouteVo.setHidden(permission.getHidden());
        frontRouteVo.setMeta(metaVo);
        return frontRouteVo;
    }


    /**
     * 封装前端路由数据
     * @param permissionList
     * @return
     */
    public static List<FrontRouteVo> build(List<Permission> permissionList){
        List<FrontRouteVo> routeVos = new ArrayList<>();
        for (Permission permission : permissionList) {
            FrontRouteVo routeVo = fillEntity(permission);
            List<Permission> children = permission.getChildren();
            if (children.size() > 0 && permission.getType() == 1) {
                routeVo.setAlwaysShow(true);
                routeVo.setRedirect("noRedirect");
                routeVo.setChildren(build(children));
            }
            routeVos.add(routeVo);
        }
        return routeVos;
    }

    /**
     * 获取路由名称
     *
     * @param permission 菜单信息
     * @return 路由名称
     */
    public static String getRouteName(Permission permission) {

        return StringUtils.capitalize(permission.getPath());
    }

    /**
     * 获取路由地址
     *
     * @param permission 菜单信息
     * @return 路由地址
     */
    public static String getRouterPath(Permission permission) {
        return "/" + permission.getPath();
    }

    /**
     * 获取组件信息
     *
     * @param permission 菜单信息
     * @return 组件信息
     */
    public static String getComponent(Permission permission) {
        String component = permission.getComponent();
        if (StringUtils.isEmpty(permission.getComponent()))
        {
            component = "Layout";
        }
        return component;
    }

    /**
     * 是否是菜单内部跳转
     * @param permission
     * @return
     */
    public static boolean isMenuFrame(Permission permission){
        return (permission.getIsOutChain() == 1 && permission.getType() == 2);
    }
}
